import request from '@/utils/request'
import { saveAs } from 'file-saver'

export default new class DownloadApi {
    name(name, isDelete = true) {
        var url = "/common/download?fileName=" + encodeURI(name) + "&delete=" + isDelete
        request({
            method: 'get',
            url: url,
            responseType: 'blob',
        }).then(res => {
            const blob = new Blob([res])
            this.saveAs(blob, decodeURI(encodeURI(name)))
        })
    }

    resource(resource) {
        var url = "/common/download/resource?resource=" + encodeURI(resource);
        request({
            method: 'get',
            url: url,
            responseType: 'blob',
        }).then(res => {
            const blob = new Blob([res.data])
            this.saveAs(blob, decodeURI(res.headers['download-filename']))
        })
    }

    zip(url, name) {
        request({
            method: 'get',
            url: url,
            responseType: 'blob',
        }).then(res => {
            const blob = new Blob([res.data], { type: 'application/zip' })
            this.saveAs(blob, name)
        })
    }

    saveAs(text, name, opts?) {
        saveAs(text, name, opts);
    }
}